/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/// <reference path="../base/lcc.ts" />
/// <reference path="../base/loading-module.ts" />
/// <reference path="../utils/js.ts" />

namespace lcc {

const TAG = "lcc/table/table-manager.ts";

/**
 * @zh
 * 索引路径
 */
export namespace INDEXPATH {
	
	/**
	 * @zh
	 * 数据表
	 */
	export let TABLE = "table";
};

/**
 * @zh
 * 数据表对象映射表<br/>
 */
export let TABLES:{[key:string]:any} = utils.js.createMap();

/**
 * @zh
 * 数据表管理器<br/>
 * 主要用于管理游戏数据表，这些表一般由策划配置<br/>
 * 数据表的合并功能
 */
export class TableManager extends LoadingModule {
	/**
	 * @zh
	 * 管理器实例
	 */
	private static _instance:TableManager;

	/**
	 * @zh
	 * 获取单例对象
	 */
	public static getInstance() : TableManager  {
		if(!TableManager._instance){
			TableManager._instance = new TableManager();
		}
		return TableManager._instance;
	}

	/**
	 * @zh
	 * 构造函数
	 */
	private constructor(){
		super();
		EventCenter.once(Events.INITIALIZE, ()=>{
			indexMgr.on("indexes_removed", this.onIndexesRemoved, this);
			indexMgr.on("indexes_loaded_" + INDEXPATH.TABLE, this.onIndexesLoaded, this);
		});
    }
	
	/**
	 * @zh
	 * 当移除索引
	 * 
	 * @internal
	 */
	onIndexesRemoved(){
		this.clearAll();
		this.onIndexesLoaded(indexMgr.getIndex(INDEXPATH.TABLE));
	}

	/**
	 * @zh
	 * 当加载索引
	 * 
	 * @param ivalue 索引对象
	 * 
	 * @internal
	 */
	async onIndexesLoaded(ivalue:Object){
		if(ivalue){
			this.setLoading(true);
			for(let t in ivalue){
				let tfiles = ivalue[t];
				for (let k in tfiles){
					let tfile:string = tfiles[k];
					let finfo = packMgr.parseFilePath(tfile);
					let table = await utils.asset.loadJson(finfo.rpath, finfo.bundle || __cc__.resources);
					if(!table){
						__cc__.error(TAG, `database file ${tfile} read fail !!!`);
					}else{
                        this.loadTable(table, tfile);
					}
				}
			}
			this.setLoading(false);
		}
	}

	/**
	 * @zh
	 * 清空所有数据表
	 */
	public clearAll(){
		for(let tbname in Object.keys(TABLES)){
			delete TABLES[tbname];
		}
    }
    
    /**
	 * @zh
     * 清空指定数据表
	 * 
     * @param tname - 数据表名称
     */
    public clearTable(tname:string){
        let table = TABLES[tname];
        if(table){
            for(let key in Object.keys(table)){
                delete table[key];
            }
        }
    }
	
	/**
	 * @zh
	 * 加载数据表
	 * 
	 * @param table - 新的表
	 * @param tfile - 表文件
	 */
	public loadTable(table:Object, tfile:string = "[unknown]"){
		utils.js.mergeMap(TABLES, table, { tag : TAG, source : tfile });
		DEBUG.TABLE && __cc__.log(TAG, `load table ${JSON.stringify(table)} from ${tfile}`);
    }
    
    /**
	 * @zh
     * 获得所有表
     */
    public getTables(){
        return TABLES;
    }
    
    /**
	 * @zh
     * 获得指定表
	 * 
     * @param tname - 数据表名称
     */
    public getTable<T>(tname:string){
        return <T>(TABLES[tname]);
    }
};

/**
 * @zh
 * 数据表管理对象
 */
export const tableMgr = TableManager.getInstance();

}
